package com.ksyzt.ksite2.server.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;

import com.google.gson.JsonObject;
import com.ksyzt.gwt.server.common.Util;
import com.ksyzt.ksite2.server.common.Application;
import com.ksyzt.ksite2.server.database.dao.IATTACHMENTDAO;
import com.ksyzt.ksite2.server.database.dao.impl.ATTACHMENTDAOImpl;
import com.ksyzt.ksite2.shared.modle.ATTACHMENTObj;

/**
 * 附件上传管理
 * 
 * @author Administrator
 * 
 */
public class AttatchmentFileUpload extends HttpServlet
{

    private static String tag = "Attatchment File Uploader";

    /**
     * Constructor of the object.
     */
    public AttatchmentFileUpload()
    {
	super();
    }

    /**
     * Destruction of the servlet. <br>
     */
    public void destroy()
    {
	super.destroy(); // Just puts "destroy" string in log
	// Put your code here
    }

    /**
     * The doGet method of the servlet. <br>
     * 
     * This method is called when a form has its tag value method equals to get.
     * 
     * @param request
     *            the request send by the client to the server
     * @param response
     *            the response send by the server to the client
     * @throws ServletException
     *             if an error occurred
     * @throws IOException
     *             if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
	    throws ServletException, IOException
    {
	request.setCharacterEncoding("UTF-8");
	response.setContentType("text/html");
	PrintWriter out = response.getWriter();
	out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
	out.println("<HTML>");
	out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
	out.println("  <BODY>");
	out.print("    This is ");
	out.print(this.getClass());
	out.println(", using the GET method");
	out.println("  </BODY>");
	out.println("</HTML>");
	out.flush();
	out.close();
    }

    /**
     * The doPost method of the servlet. <br>
     * 
     * This method is called when a form has its tag value method equals to
     * post.
     * 
     * @param request
     *            the request send by the client to the server
     * @param response
     *            the response send by the server to the client
     * @throws ServletException
     *             if an error occurred
     * @throws IOException
     *             if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
	    throws ServletException, IOException
    {

	System.out.println(tag + " start");
	request.setCharacterEncoding("UTF-8");
	response.setContentType("text/html");
	response.setCharacterEncoding("UTF-8");
	PrintWriter out = response.getWriter();

	JsonObject json = new JsonObject();

	Application app = new Application(request, response);

	String basePath = app.getBasePath();
	JsonObject r = new JsonObject();
	// 设置保存上传文件的目录
	String upext = "txt,rar,zip,jpg,jpeg,gif,png,swf,wmv,avi,wma,mp3,mid,tar,gz,doc,docx,pdf,xls,xlsx"; // 上传扩展名
	String err = "";
	String immediate = "";
	String attach_dir;
	String attach_subdir;
	String filename = "";
	String extension = "";
	String target = "";
	String filetype = "";

	String uploadDir = getServletContext().getRealPath("upload");
	File fUploadDir = new File(uploadDir);

	if (!fUploadDir.exists())
	{
	    fUploadDir.mkdirs();
	}

	DiskFileUpload fu = new DiskFileUpload();
	// 最多上传10M数据
	fu.setSizeMax(-1);
	// 超过1M的字段数据采用临时文件缓存
	fu.setSizeThreshold(1024 * 1024);
	// 采用默认的临时文件存储位置
	// fu.setRepositoryPath(...);
	// 设置上传的普通字段的名称和文件字段的文件名所采用的字符集编码
	fu.setHeaderEncoding("UTF-8");

	// 得到所有表单字段对象的集合
	List fileItems = null;
	try
	{
	    fileItems = fu.parseRequest(request);
	} catch (FileUploadException e)
	{
	    err = "解析数据时出现如下问题：" + e.getMessage();
	    e.printStackTrace();
	}
	if (fileItems != null)
	{
	    // 处理每个表单字段
	    Iterator i = fileItems.iterator();
	    while (i.hasNext())
	    {
		FileItem fi = (FileItem) i.next();
		if (fi.isFormField())
		{
		    String content = new String(fi.getString("UTF-8"));

		    String fieldName = fi.getFieldName();
		    request.setAttribute(fieldName, content);

		    System.out.println(tag + ">" + fieldName + ":" + content);
		}
	    }
	}
	/*** 确定必要的变量 ******/
	String nid = (String) request.getAttribute("nid");
	String title = (String) request.getAttribute("title");

	System.out.println("attatchement uploader>" + nid + "," + title);
	String contenttype = "";
	if (fileItems != null)
	{
	    // 处理每个表单字段
	    Iterator i = fileItems.iterator();
	    while (i.hasNext())
	    {
		FileItem fi = (FileItem) i.next();
		if (fi.isFormField())
		{

		} else
		{
		    try
		    {
			System.out.println(tag + ">parse item:"
				+ fi.getFieldName());
			contenttype = fi.getContentType();
			String pathSrc = fi.getName();
			if (pathSrc.trim().equals(""))
			{
			    continue;
			}
			// 取上载文件后缀名
			extension = pathSrc
				.substring(pathSrc.lastIndexOf(".") + 1);
			extension = extension.toLowerCase();
			if (("," + upext + ",").indexOf("," + extension + ",") < 0)
			{
			    err = "上传文件扩展名必需为：" + upext;
			} else
			{
			    Date now = new Date();
			    attach_subdir = "day_"
				    + Util.getDateString(now.getTime(),
					    "yyMMdd");

			    attach_dir = fUploadDir + "/" + attach_subdir + "/";
			    File tempFile = new File(attach_dir);
			    if (!tempFile.exists())
			    {
				tempFile.mkdirs();
			    }

			    // 生成随机文件名

			    filename = Util.randomString(8) + "." + extension;

			    target = "upload/" + attach_subdir + "/" + filename;
			    json.addProperty("path", target);

			    File pathDest = new File(fUploadDir + "/"
				    + attach_subdir + "/" + filename);
			    fi.write(pathDest);

			    System.out.println(tag + ">" + nid + "," + title
				    + "," + target + "," + contenttype);
			    /*************** save to attatchment table ********/
			    try
			    {
				if (nid != null && !nid.equals(""))
				{

				    IATTACHMENTDAO dao = new ATTACHMENTDAOImpl(
					    Application.getConnection());
				    ATTACHMENTObj att = new ATTACHMENTObj();
				    att.setCDATE(Util.getCurrentSQLTimestamp());
				    att.setDCOUNT(0);
				    att.setTAG(Util.randomString(12));
				    att.setFILEPATH(target);
				    att.setNID(nid);
				    att.setFTYPE(contenttype);
				    att.setTITLE(title);
				    dao.insertObject(att);
				}
			    } catch (SQLException e)
			    {
				err = e.getMessage();
				e.printStackTrace();
			    }
			}
		    } catch (Exception e)
		    {

			err = "存储文件时出现如下问题：" + e.getMessage();
			e.printStackTrace();
		    } finally
		    // 总是立即删除保存表单字段内容的临时文件
		    {
			fi.delete();
		    }
		}
	    }
	}

	int msgtype = 2; // 返回上传参数的格式：1，只返回url，2，返回参数数组
	target = basePath + target;
	if (immediate != null && immediate.equals("1"))
	{
	    target = "!" + target;
	}

	if (msgtype == 1)
	{
	    r.addProperty("msg", (target));
	} else
	{
	    json.addProperty("url", (target));
	    // json.setAttribute("localname",localname);
	    json.addProperty("id", ("1"));
	    r.addProperty("msg", (target));
	    r.add("data", json);
	}

	r.addProperty("err", (err));

	out.print(r.toString());

	out.flush();
	out.close();
    }

    /**
     * Initialization of the servlet. <br>
     * 
     * @throws ServletException
     *             if an error occurs
     */
    public void init() throws ServletException
    {
	// Put your code here
    }
}
